import {defineStore} from 'pinia'
import {ref} from "vue";
import UserApi from '@/api/user.js'
import {RES_CODE} from '@/enum/codeEnum.js'
import {ElMessage} from "element-plus";
import {useRouter} from 'vue-router'
import {removeToken, setToken} from "@/utils/auth.js";


export const useUserStore = defineStore('user', () => {

    let userInfo = ref({})
    let roles = ref([])
    let token = ref('')

    const router = useRouter()

    /*登录*/
    function login(data) {
        UserApi.login(data).then(res => {
            if (res.data.code === RES_CODE.SUCCESS) {
                setToken(res.data.data.token)
                token.value = res.data.data.token
                ElMessage.success("登录成功")
                router.push('/home')
            } else {
                ElMessage.error(res.data.msg)
            }
        })
    }

    /*退出登录*/
    function logout() {
        UserApi.logout().then(res => {
            if (res.data.code === RES_CODE.SUCCESS) {
                ElMessage.success("退出成功")
                userInfo.value = {}
                removeToken()
                token.value = ''
                roles.value = []
                router.push('/login')
            } else {
                ElMessage.error(res.data.msg)
            }
        })
    }

    /*获取用户信息*/
    function getMeInfo() {
        return new Promise((resolve, reject) => {
            UserApi.getMeInfo().then(res => {
                if (res.data.code === RES_CODE.SUCCESS) {
                    userInfo.value = res.data.data
                    roles.value = res.data.data.roles
                    resolve(res.data.data)
                } else {
                    ElMessage.error(res.data.msg)
                    reject()
                }
            })
        })
    }
    function reset(){
        userInfo.value = {}
        token.value = ''
        roles.value = []
    }

    return {
        userInfo,
        roles,
        token,
        login,
        logout,
        getMeInfo,
        reset
    }
}, {
    persist: {
        key: 'user',
        storage: localStorage
    }
})
